package com.bookstore.client.cart.handler;

import com.bookstore.client.product.service.IProductService;
import com.bookstore.commons.beans.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * company: www.abc.com
 * Author: Administrator
 * Create Data: 2021/6/1 0001
 */
@Controller
@RequestMapping("/client/cart")
public class CartHandler {

    @Autowired
    IProductService productService;

    //添加到购物车  保存在session  使用map
    //map中 商品为关键字  购买的数量为值
    @RequestMapping("/addCart")
    public String addCart(String id, HttpSession session){
        //查询放到购物车的商品信息
        Product product = productService.findProductById(id);
        //从session获取购物车
        Map<Product,Integer> cart = (Map<Product, Integer>) session.getAttribute("cart");
        if(cart == null){
            //创建购物车
            cart = new HashMap<Product,Integer>();
        }

        //put方法有返回值，返回值是原来value的值
        Integer count = cart.put(product,1);
        //如果添加的商品相同则 count+1    不相同则为1
        if(count != null){
            cart.put(product,count+1);
            //如果加一后大于商品库存，则不变
            if ((count+1)>product.getPnum()){
                cart.put(product,count);
            }
        }
        session.setAttribute("cart",cart);
        return "redirect:/client/cart.jsp";
    }

    //改变商品数量
    @RequestMapping("changeCart")
    public String changeCart(String id,Integer count,HttpSession session){

        System.out.println(count);
        Product product = productService.findProductById(id);

        Map<Product,Integer> cart = (Map<Product, Integer>) session.getAttribute("cart");
        //如果商品数量为0，从购物车删除
        if (count == 0){
            cart.remove(product);
        }
        else{
            cart.put(product,count);
        }
        return "redirect:/client/cart.jsp";
    }
}
